package com.bjsxt.userscenter.springmvc.interceptor;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.bjsxt.userscenter.auth.pojo.ARoleMenu;
import com.bjsxt.userscenter.auth.service.IAuthService;
import com.bjsxt.userscenter.common.util.ConstatFinalUtil;
import com.bjsxt.userscenter.users.pojo.AAdmins;

/**
 * 拦截器
 * @author WangshSxt
 */
@Component("authInterceptor")
public class AuthInterceptor extends HandlerInterceptorAdapter
{
	@Resource
	private IAuthService authService;
	
	/**
	 * @return true:放行,false:拦截
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		String info = "" ; 
		/* 如何验证是否登陆呢? */
		HttpSession session = request.getSession() ;
		AAdmins admins = (AAdmins) session.getAttribute("admins");
		if(admins == null)
		{
			/* 登陆失败,客户端跳转到登陆页面
			 * 跳转到Controller中的方法
			 *  */
			/* 非法访问,请先登陆 */
			info = ConstatFinalUtil.INFO_JSON.getString("7") ; 
			session.setAttribute("info", info);
			response.sendRedirect(request.getContextPath() + "/login.htm");
			return false;
		}
		
		if(admins.getId() == 1)
		{
			return true ; 
		}
		
		/*
		 * 刚刚分配的权限,基于角色分配的;这个角色下面的菜单,木有权限访问?做一个提示页面?
			刚登陆的账号肯定可以定位到一个角色
			查询角色对应的菜单
			每一次访问的时候,都可以获取到当前访问的url
			菜单表中也有url,存储的是完整url的一部分.
			比对:
			
			实现步骤:
		 */
		
		/*
		 * ~获取当前访问的URL
		 * http://localhost:8080/userscenter-back/back/admins/main.htm#roleMenuInsert
		 * 数据库存储的是:/back/admins/leftMenu.htm?operType=system
		 * */
		String currUrl = request.getRequestURL() + "";
		ConstatFinalUtil.SYS_LOGGER.info("getRequestURL:",request.getRequestURL());
		ConstatFinalUtil.SYS_LOGGER.info("getRequestURI:",request.getRequestURI());
		/*~查询管理员对应的角色,
		 * 查询角色对应的菜单
		 * */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("roleId", admins.getRoleId());
		Map<String, Object> resultMap = this.authService.findCondListRoleMenuService(null, condMap);
		List<ARoleMenu> roleMenuList = (List<ARoleMenu>) resultMap.get("list");
		
		/**
		 * 循环角色对应的菜单
		 * 拿着当前的url和菜单对应的url比对
		 */
		for (Iterator iterator = roleMenuList.iterator(); iterator.hasNext();)
		{
			ARoleMenu roleMenu = (ARoleMenu) iterator.next();
			if(currUrl.indexOf(roleMenu.getMenu().getUrl()) != -1)
			{
				/* 找到了url
				 * 放行 
				 * */
				return true ; 
			}
		}
		
		/*
		 * 找不到对应的url,菜单
		 * 木有权限
		 * */
		response.sendRedirect(request.getContextPath() + "/info/error.jsp");
		return false ; 
	}
	
}
